<?php
/**
 * 轻舟CMS(QZLOG)
 *
 * 一款基于PHP+MYSQL的开源内容管理系统，模板标签简单、可扩展性强，利于二次开发，轻松建站的首选利器。
 *
 * @package     QZLOG
 * @license     http://www.qzlog.com/license
 * @link        http://www.qzlog.com
 * @mail        info@shyohan.com
 * @since       Version 3.0
 * @copyright   Copyright (c) 2015 - 2017 上海优翰信息科技有限公司. All rights reserved.
 */

defined('IN_QZLOG') OR exit('QZLOG:No direct script access allowed!');

/**
 * 权限分组模型
 * @author LINK <link@shyohan.com>
 */
class AuthGroupModel extends ViewModel
{
    public $table = "auth_group";

    /**
     * 表单验证
     * @author LINK <link@shyohan.com>
     * @var array
     */
    public $validate = array(
        array('title', 'nonull', '权限组名不能为空 ', 2, 1),
        array('title', 'IsGroupname', '权限组名已经存在 ', 2, 1)
    );

    /**
     * 验证账号
     * @author LINK <link@shyohan.com>
     * @param $name
     * @param $value
     * @param $msg
     * @param $arg
     * @return bool
     */
    public function IsGroupname($name, $value, $msg, $arg)
    {
        $map['title'] = $value;
        if (M('auth_group')->find($map)) {
            return $msg;
        } else {
            return true;
        }
    }

    /**
     * 添加权限组
     * @author LINK <link@shyohan.com>
     * @return bool
     */
    public function addGroup()
    {
        if ($this->create()) {
            $this->data['type'] = 1;
            $this->data['status'] = 1;
            if ($this->add()) {
                return true;
            } else {
                $this->error = '添加失败';
                return false;
            }
        }
    }

    /**
     * 修改权限组
     * @author LINK <link@shyohan.com>
     * @return bool
     */
    public function editGroup()
    {
        if ($this->create()) {
            if ($this->save()) {
                return true;
            } else {
                $this->error = '修改失败';
            }
        }
    }

    /**
     * 删除权限组
     * @author LINK <link@shyohan.com>
     * @return bool
     */
    public function delGroup()
    {
        $id = Q("id", 0);
        if (!$id) {
            $this->error = '参数错误';
            return false;
        }
        if (in_array(1, explode(',', $id))) {
            $this->error = '不允许删除默认组';
            return false;
        }
        $map['id'] = array('in', explode(",", $id));
        if ($this->where($map)->del()) {
            return true;
        } else {
            $this->error = '删除失败';
        }
    }

    /**
     * 改变权限组状态
     * @author LINK <link@shyohan.com>
     * @return bool
     */
    public function changeStatusGroup()
    {
        $id = Q("id", 0);
        $method = Q("method");
        if (!$id) {
            $this->error = '请选择要操作的数据';
            return false;
        }
        if (in_array(1, explode(',', $id))) {
            $this->error = '不允许操作默认分组';
            return false;
        }
        switch (strtolower($method)) {
            case 'forbid':
                if ($this->where(array('id' => array('in', explode(",", $id))))->save(array('status' => 0))) {
                    return true;
                } else {
                    $this->error = '禁用失败!';
                    return false;
                }
                break;
            case 'resume':
                if ($this->where(array('id' => array('in', explode(",", $id))))->save(array('status' => 1))) {
                    return true;
                } else {
                    $this->error = '恢复失败!';
                    return false;
                }
                break;
            default:
                $this->error = '参数非法';
                return false;
        }
    }

    /**
     * 用户组数据写入/更新
     * @author LINK <link@shyohan.com>
     * @return bool
     */
    public function writeGroup()
    {
        if (isset($_POST['rules']) && isset($_POST['id'])) {
            $data = array();
            $id = Q('post.id');
            $rules = Q('post.rules');
            sort($rules);
            $data['rules'] = implode(',', array_unique($rules));
            if ($this->where(array('id' => $id))->save($data)) {
                return true;
            } else {
                $this->error = '操作失败!';
                return false;
            }
        } else {
            $this->error = '参数非法';
            return false;
        }
    }

    /**
     * 添加用户到用户组
     * @author LINK <link@shyohan.com>
     * @return bool
     * 示例: 把uid=1,2的用户添加到group_id为2的组 `$this->addToGroup('1,2','2');
     */
    public function addUserToGroup()
    {
        $uid = Q('post.id');
        $gid = Q('post.group_id');
        if (empty($uid) || empty($gid)) {
            $this->error = '参数有误!';
            return false;
        }

        if (is_numeric($uid)) {
            if (in_array($uid, C('USER_ADMINISTRATOR'))) {
                $this->error = '不允许操作超级管理员!';
                return false;
            }
            if (!M('member')->where(array('id' => $uid))->find()) {
                $this->error = '用户不存在!';
                return false;
            }
        }

        if ($gid && !$this->checkGroupId($gid)) {
            return false;
        }
        if ($this->addToGroup($uid, $gid)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查用户组是否全部存在
     * @author LINK <link@shyohan.com>
     * @param $modelname
     * @param $mid
     * @param string $msg
     * @return bool
     */
    public function checkGroupId($gid, $msg = '以下用户组id不存在:')
    {
        if (is_array($gid)) {
            $count = count($gid);
            $ids = implode(',', $gid);
        } else {
            $gid = explode(',', $gid);
            $count = count($gid);
            $ids = $gid;
        }

        $s = M('auth_group')->where(array('id' => array('IN', $ids)))->getField('id', true);
        if (count($s) === $count) {
            return true;
        } else {
            $diff = implode(',', array_diff($gid, $s));
            $this->error = $msg . $diff;
            return false;
        }
    }

    /**
     * 把用户添加到用户组,支持批量添加用户到用户组
     * @author LINK <link@shyohan.com>
     *
     * 示例: 把uid=1的用户添加到group_id为1,2的组 `AuthGroupModel->addToGroup(1,'1,2');`
     */
    public function addToGroup($uid, $gid)
    {
        $uid = is_array($uid) ? implode(',', $uid) : trim($uid, ',');
        $gid = is_array($gid) ? $gid : explode(',', trim($gid, ','));
        $access = M('auth_group_access');
        //为单个用户批量添加用户组时,先删除旧数据
        $del = $access->where(array('uid' => array('in', $uid)))->del();

        $uid_arr = explode(',', $uid);
        $add = array();
        if ($del !== false) {
            foreach ($uid_arr as $u) {
                foreach ($gid as $g) {
                    if (is_numeric($u) && is_numeric($g)) {
                        if (in_array($u, C('USER_ADMINISTRATOR'))) {
                            $this->error = '不允许操作超级管理员!';
                            return false;
                        }
                        if (!M('member')->where(array('id' => $u))->find()) {
                            $this->error = '用户不存在!';
                            return false;
                        }
                        $access->add(array('group_id' => $g, 'uid' => $u));
                    }
                }
            }
        }
        if ($this->error) {
            if (count($uid_arr) == 1 && count($gid) == 1) {
                //单个添加时定制错误提示
                $this->error = "不能重复添加";
            }
            return false;
        } else {
            return true;
        }
    }
}